App.controller("addProductCtrl",function($scope, $rootScope, $location, $http, $compile, $stateParams, $timeout, path, publicService) {
	var params = JSON.parse($stateParams.params);
	console.log("路由参数：",params);
	
	$scope.form = {};		//表单
	$scope.form.brandProductImgEntities = [];		//产品展示图
	$scope.form.brandProductSeriesEntities = [];	//所属分类
	$scope.form.brandProductSalesattrEntities = [];	//颜色分类
	
	$scope.submit_show = true;				//提交（显示）
	
	var classData = [];		//分类数据
	var classTree = null	//分类树;
	
	var limitParam1 = {imageSize:150, format:"jpg"};		//产品展示图
	var limitParam2 = {imageSize:80, format:"jpg"};			//颜色分类图
	var editor = null;	//编辑器
	var productInfo = null;		//产品信息
	
	var color_index = 0;
	var priceUnit = ["元/片","元/米","元/平米","元/件","元/延米","元/个","元/套","元/L","元/桶","元/卷","元/块","元/樘","元/组","元/片","元/立方米","元/立方厘米","元/盒","元/袋","元/g","元/kg","元/毫米","元/厘米","元/分米","元/毫升","元/扇","元/张"];
	var alertModel = {};	//alert模态框
	
	
	
	//初始化图文编辑器
	$scope.initEditor = function(editorId){
		var option = {initialFrameHeight:400};

		if(UE.getEditor(editorId,option).container){
			UE.getEditor(editorId).destroy();
		}
		editor = UE.getEditor(editorId,option);
	}
	
	//初始化【计价单位】
	$scope.initPriceUnit = function(containerId){
		$("#"+containerId).kendoComboBox({
			placeholder: "请选择",
		    filter: "contains",
		    dataSource: priceUnit
		});
	}
	
	//初始化【是否新品】
	$scope.initIsNew = function(containerId){
		$("#"+containerId).kendoDropDownList({
			dataTextField: "text",
		    dataValueField: "value",
		    dataSource: [
					 {
						value: "",
						text: "请选择"
					 },		            
		             {
		            	value: 1,
		 				text: "是"
		             },
		             {
		            	value: 0,
		 				text: "否"
		             }
            ],
            change: function(e) {
	    	    var value = this.value();
	    	    if(value==1){
	    	    	$("#upTime_show").show();
	    	    }else{
	    	    	$("#upTime_show").hide();
	    	    }
	    	    
	    	    
		    }
		});
	}
	
	//提示信息
	$scope.alertMessage = function(message){
		alertModel.pannel = jqueryAlert({
			content: message,
			modal: true
		});
	}
	
	//增加颜色
	$scope.addColor = function(isFirst){
		var html = '';
		color_index ++;
		
		var containerId = "color"+color_index;
		var imgId =	"color"+color_index+"_img";
		var imgUrlId = "color"+color_index+"_url";
		
		var add_remove_html = '';
		if(isFirst){
			add_remove_html = '<button class="k-button k-state-default operate" ng-click="addColor(false)">添加</button>';
		}else{
			add_remove_html = '<button class="k-button k-state-default operate" ng-click="removeColor($event)">删除</button>';
		}
		
		html += ('<div class="form-horizontal">'
					+'<div class="form-group">'
						+'<div class="col-sm-9" id="colorIndex_'+color_index+'">'
							+'<div class="form-horizontal">'
								+'<div class="form-group">'
									+'<div class="col-sm-12">'
										+'<input type="text" class="form-control" placeholder="颜色名称"/>'
									+'</div>'
								+'</div>'
							+'</div>'
							+$scope.getColorChildren_html(color_index,true)
						+'</div>'
						+'<div class="col-sm-2">'
							+'<div class="logoContainer2">'
								+'<div class="imgBackground1">'
									+'<span class="glyphicon glyphicon-plus"></span>'
								+'</div>'
								+'<div class="imgBackground2" id="'+imgId+'"></div>'
								+'<input type="file" name="file" id="'+containerId+'"/>'
								+'<input type="hidden" id="'+imgUrlId+'"/>'
							+'</div>'
						+'</div>'
						+'<div class="col-sm-1">'
							+add_remove_html
						+'</div>'
					+'</div>'
				+'</div>');
		
		
		
		html = $compile(html)($scope);   //angularJs代码需要动态编译
		$("#colorContainer").append(html);
		
		publicService.uploadImage(containerId,imgId,imgUrlId,limitParam2);
	}
	
	//移除颜色
	$scope.removeColor = function($event){
//		$("#colorIndex_"+color_index).parent("div").parent("div").remove();
		angular.element($event.target).parent("div").parent("div").parent("div").remove();
	}
	
	//获取颜色子集html
	$scope.getColorChildren_html = function(color_index,isFirst){
		var html = '';
		
		var add_remove_html = '';
		if(isFirst){
			add_remove_html = '<i class="fa fa-plus width20 operate" ng-click="addColorChildren('+color_index+')"></i>';
		}else{
			add_remove_html = '<i class="fa fa-minus width20 operate" ng-click="removeColorChildren($event,'+color_index+')"></i>';
		}
		
		html += ('<div class="form-horizontal">'
					+'<div class="form-group">'
						+'<div class="col-sm-3">'
							+add_remove_html
							+'<input type="text" class="form-control width80" placeholder="添加规格"/>'
						+'</div>'
						+'<div class="col-sm-3">'
							+'<input type="text" class="form-control" placeholder="添加型号"/>'
						+'</div>'
						+'<div class="col-sm-3">'
							+'<div class="width90">'
								+'<input type="number" class="form-control" placeholder="添加价格"/>'
							+'</div>'
							+'<div class="width10 control-label">元</div>'
						+'</div>'
						+'<div class="col-sm-3">'
							+'<div class="width90">'
								+'<input type="number" class="form-control" placeholder="添加库存数量"/>'
							+'</div>'
							+'<div class="width10 control-label">件</div>'
						+'</div>'
						+'<div>'
							+'<input type="hidden"/>'
						+'</div>'
					+'</div>'
				+'</div>');
		
		return html;
	}
	
	//增加颜色子集
	$scope.addColorChildren = function(color_index){
		var html = $scope.getColorChildren_html(color_index,false);

		html = $compile(html)($scope);   //angularJs代码需要动态编译
		$("#colorIndex_"+color_index).append(html);
	}
	
	//移除颜色子集
	$scope.removeColorChildren = function($event){
		var id = angular.element($event.target).parent("div").parent("div").find("input:hidden").val();
		if(id){
			$scope.deleteColorChildren(id);
		}
		angular.element($event.target).parent("div").parent("div").parent("div").remove();
	}
	
	//删除颜色子集
	$scope.deleteColorChildren = function(id){ 
		$http({
			   url:	path+'/server/removeproductsaleattr/'+id,
			   method: 'GET'   
		}).success(function(data){
			if(data.code==0){  //成功
				console.log("【删除颜色子集】success");
			}else if(data.code==1){  //失败
				console.log("【删除颜色子集】fail");
			}
		}).error(function(data){
			alert(data);   
		})
	}
	
	//获取分类数据
	$scope.getClassData = function(checkedDataList){ 
		$http({
			   url:	path+'/server/querybrandclassifyentityall',
			   method: 'GET'   
		}).success(function(data){
			if(data.code==0){  //成功
				classData = data.result;
				classData = $scope.packZtreeDataForChecked(classData,checkedDataList);
				
				var paramObj = {pIdKey:"p_id"};
				classTree = publicService.initZtree("ztree",classData,paramObj);
			}else if(data.code==1){  //失败
				
			}
		}).error(function(data){
			alert(data);   
		})
	}
	
	//封装选中的树形插件数据
	$scope.packZtreeDataForChecked = function(allData,checkedData){
		$.each(allData, function(index, OneObj){
			if(checkedData && checkedData.length>0){
				if(publicService.isExitInArray(checkedData,"series_id",OneObj.id)){
					OneObj.checked = true;
				}
			}
		});
		
		return allData;
	}
	
	
	
	//表单提交
	$scope.formSubmit = function(){
		//展示图
		for (var i = 1; i <= 5; i++) {
			var imageObj = {
					imgurl: $("#upload"+i+"_url").val(),
					id: $("#upload"+i+"_image_id").val()
			};
			if(imageObj.imgurl){
				$scope.form.brandProductImgEntities.push(imageObj);
			}
		}
		$scope.form.product_unit = $("#priceUnit").data("kendoComboBox").value();	//计价单位
		$scope.form.isnew = $("#isNew").data("kendoDropDownList").value();	//是否新品
		$scope.form.new_time = $("#startTime").val();	//上新时间
		//所属分类
		var checkedNodes = classTree.ztree.getCheckedNodes(true);
    	$.each(checkedNodes, function(index, OneObj){
			var classifyObj = {
					series_id: OneObj.id
			};
			$scope.form.brandProductSeriesEntities.push(classifyObj);
		});
    	//颜色分类 
    	var colorArr = $("#colorContainer").children("div");
    	$.each(colorArr, function(index, OneObj){
    		var column_1 = $(OneObj).children("div").children("div:nth(0)");
    		var column_2 = $(OneObj).children("div").children("div:nth(1)");	//图片
    		var color_url = $(column_2).find("input[type='hidden']").val();
    		
    		var rowArr = $(column_1).children("div");
    		var color = "";
    		$.each(rowArr, function(index_2, OneObj_2){
    			if(index_2==0){
    				color = $(OneObj_2).find("input").val();
    			}else{
    				var row = $(OneObj_2).children("div");
    				
    				var colorObj = {
    						color: color,
    						standard: $(row).children("div:nth(0)").find("input").val(),
    						model: $(row).children("div:nth(1)").find("input").val(),
    						price: $(row).children("div:nth(2)").find("input").val(),
    						stock: $(row).children("div:nth(3)").find("input").val(),
    						id: $(row).children("div:nth(4)").find("input").val(),
    						color_url: color_url
    				};
    				$scope.form.brandProductSalesattrEntities.push(colorObj);
    			}
    		});
		});
    	$scope.form.description = editor.getContent();		//产品详情图
	
		var url = '';
		if(params.method=="add"){
			url = path+'/server/addproduct';
		}else if(params.method=="edit"){
			url = path+'/server/modifyproduct';
			$scope.form.id = productInfo.id;
		}
		
		$http({
			   url: url,
			   method: 'POST',
			   data: angular.toJson($scope.form)
		}).success(function(data){
			if(data.code==0){
				$scope.alertMessage("成功！");
				$location.path("/"+params.backUrl);
			}else{
				$scope.alertMessage("失败！");
			}
		}).error(function(data){
			console.warn(data);   
		})
	}
	
	//获取产品信息
	$scope.getProductInfo = function(id){ 
		$http({
			   url:	path+'/server/getproduct/'+id,
			   method: 'GET'   
		}).success(function(data){
			if(data.code==0){  //成功
				productInfo = data.result;
				
				var imageArr = productInfo.brandProductImgEntities;		//展示图
				$.each(imageArr, function(index, OneObj){
					var imageIndex = index+1;
					publicService.showUploadImage("upload"+imageIndex+"_img","upload"+imageIndex+"_url",OneObj.imgurl);
					$("#upload"+imageIndex+"_image_id").val(OneObj.id);
	    		});
				$scope.form.product_title = productInfo.product_title;
				$scope.form.product_sort = productInfo.product_sort;
				$("#priceUnit").data("kendoComboBox").value(productInfo.product_unit);	//计价单位
				$("#isNew").data("kendoDropDownList").value(productInfo.isnew);	//是否新品
				if(productInfo.isnew==1){
					$("#upTime_show").show();
					$("#startTime").val(productInfo.new_time);	//上新时间
				}
				$scope.getClassData(productInfo.brandProductSeriesEntities);		//获取分类数据
				//颜色分类
				var colorArr = productInfo.brandProductSalesattrEntities;
				var color_first_value = '';
				var color_first_index = 1;
				$.each(colorArr, function(index, OneObj){
					var color_now = OneObj.color;
					if((color_first_value=="") || (color_first_value!="" && color_first_value!=color_now)){
						if(color_first_value!=""){
							$scope.addColor();		//增加颜色
						}
						color_first_value = color_now;
						color_first_index = 1;
					}else{
						$scope.addColorChildren(color_index);		//增加颜色子集
					}
					
					var colorOne = $("#colorContainer").children("div:nth("+(color_index-1)+")").children("div");
					var column_1 = $(colorOne).children("div:nth(0)");
					var column_2 = $(colorOne).children("div:nth(1)");		//图片
					publicService.showUploadImage("color"+color_index+"_img","color"+color_index+"_url",OneObj.color_url);
					
					if(color_first_index==1){
						$(column_1).children("div:nth(0)").find("input").val(OneObj.color);		//颜色
					}else{
						
					}
					
					var colorChildren = $(column_1).children("div:nth("+color_first_index+")").children("div");
					$(colorChildren).children("div:nth(0)").find("input").val(OneObj.standard);		//规格
					$(colorChildren).children("div:nth(1)").find("input").val(OneObj.model);		//型号
					$(colorChildren).children("div:nth(2)").find("input").val(OneObj.price);		//价格
					$(colorChildren).children("div:nth(3)").find("input").val(OneObj.stock);		//库存
					$(colorChildren).children("div:nth(4)").find("input").val(OneObj.id);	//id
					
					color_first_index ++;
	    		});
				
				$timeout(function(){
					editor.setContent(productInfo.description);		//产品详情图
					if(params.method=="look"){
						$("input").attr("readonly","readonly");
						$(".operate").hide();
						editor.setDisabled("fullscreen");
					}
			    }, 1000);
				
			}else if(data.code==1){  //失败
				console.log("失败！");
			}
		}).error(function(data){
			alert(data);   
		})
	}
	
	
	
	
	for (var i = 1; i <= 5; i++) {
		publicService.uploadImage("upload"+i,"upload"+i+"_img","upload"+i+"_url",limitParam1);
	}
	$scope.initPriceUnit("priceUnit");		//初始化【计价单位】
	$scope.initIsNew("isNew");				//初始化【是否新品】
	publicService.initDateTime("startTime");	//上新时间
	$scope.initEditor("editor");	//初始化编辑器
	$scope.addColor(true);		//增加颜色

	
	if(params.method=="add"){
		
		$scope.getClassData();		//获取分类数据
		
		
	}else if(params.method=="edit"){
		$scope.getProductInfo(params.id);
	}else if(params.method=="look"){
		$scope.getProductInfo(params.id);
		
		$scope.submit_show = false;
		$("#priceUnit").data("kendoComboBox").readonly(true);
		$("#isNew").data("kendoDropDownList").readonly(true);
		$("#startTime").data("kendoDateTimePicker").readonly(true);
	
	}


	
	
	
});